<template>
  <div class="report-generator-page">
    <el-card shadow="hover">
      <!-- 页面头部 -->
      <div slot="header" class="page-header">
        <div class="header-left">
          <h2 class="page-title">报告生成</h2>
          <el-tag type="info">项目: {{ currentProjectName }}</el-tag>
        </div>
        <div class="header-actions">
          <el-button
            type="primary"
            @click="batchGenerate"
            icon="el-icon-download"
            :disabled="selectedRows.length === 0"
          >
            批量生成 ({{ selectedRows.length }})
          </el-button>
          <el-button
            @click="refresh"
            icon="el-icon-refresh"
          >
            刷新
          </el-button>
        </div>
      </div>

      <!-- 筛选条件 -->
      <div class="filter-container">
        <el-form :model="filterForm" inline>
          <el-form-item label="模板类型">
            <el-select v-model="filterForm.templateType" clearable>
              <el-option label="原始记录" value="record"></el-option>
              <el-option label="检测报告" value="report"></el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item label="样品编号">
            <el-input
              v-model="filterForm.sampleNo"
              placeholder="输入样品编号"
              clearable
            ></el-input>
          </el-form-item>
          
          <el-form-item label="生成时间">
            <el-date-picker
              v-model="filterForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="handleFilter">查询</el-button>
            <el-button @click="resetFilter">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 数据表格 -->
      <div class="data-table">
        <el-table
          :data="dataList"
          v-loading="loading"
          @selection-change="handleSelectionChange"
          style="width: 100%"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          
          <el-table-column prop="sampleNo" label="样品编号" width="150">
            <template #default="scope">
              <span class="sample-no">{{ scope.row.sampleNo }}</span>
            </template>
          </el-table-column>
          
          <el-table-column prop="projectName" label="项目名称" min-width="200">
            <template #default="scope">
              <div class="project-info">
                <div class="project-name">{{ scope.row.projectName }}</div>
                <div class="standard-code">{{ scope.row.standardCode }}</div>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column prop="testDate" label="检测日期" width="120">
            <template #default="scope">
              {{ formatDate(scope.row.testDate) }}
            </template>
          </el-table-column>
          
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="getStatusTag(scope.row.status)" size="small">
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="lastGenerateTime" label="上次生成" width="180">
            <template #default="scope">
              {{ scope.row.lastGenerateTime ? formatDate(scope.row.lastGenerateTime) : '未生成' }}
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="300" fixed="right">
            <template #default="scope">
              <el-button
                type="text"
                size="mini"
                @click="viewData(scope.row)"
                icon="el-icon-view"
              >
                查看数据
              </el-button>
              <el-button
                type="text"
                size="mini"
                @click="generateSingle(scope.row)"
                icon="el-icon-download"
              >
                生成报告
              </el-button>
              <el-button
                type="text"
                size="mini"
                @click="viewHistory(scope.row)"
                icon="el-icon-time"
              >
                生成历史
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.current"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
        >
        </el-pagination>
      </div>
    </el-card>

    <!-- 数据查看对话框 -->
    <el-dialog
      title="查看检测数据"
      :visible.sync="dataViewDialog.visible"
      width="80%"
      top="5vh"
    >
      <test-data-view
        v-if="dataViewDialog.visible"
        :test-data="dataViewDialog.data"
      />
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="dataViewDialog.visible = false">关闭</el-button>
        <el-button type="primary" @click="generateFromDataView">
          生成报告
        </el-button>
      </div>
    </el-dialog>

    <!-- 生成选项对话框 -->
    <el-dialog
      :title="generateDialog.title"
      :visible.sync="generateDialog.visible"
      width="500px"
    >
      <el-form :model="generateDialog.form" label-width="100px">
        <el-form-item label="模板选择">
          <el-select v-model="generateDialog.form.templateId" style="width: 100%">
            <el-option-group
              v-for="group in templateGroups"
              :key="group.type"
              :label="group.label"
            >
              <el-option
                v-for="template in group.templates"
                :key="template.id"
                :label="template.name"
                :value="template.id"
              ></el-option>
            </el-option-group>
          </el-select>
        </el-form-item>
        
        <el-form-item label="文档格式">
          <el-radio-group v-model="generateDialog.form.format">
            <el-radio label="word">Word文档</el-radio>
            <el-radio label="pdf">PDF文档</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="文件名称">
          <el-input
            v-model="generateDialog.form.filename"
            placeholder="自动生成文件名称"
          ></el-input>
        </el-form-item>
        
        <el-form-item label="包含内容">
          <el-checkbox-group v-model="generateDialog.form.includes">
            <el-checkbox label="rawData">原始数据</el-checkbox>
            <el-checkbox label="calculations">计算结果</el-checkbox>
            <el-checkbox label="charts">图表</el-checkbox>
            <el-checkbox label="signatures">签名栏</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="generateDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="confirmGenerate" :loading="generating">
          开始生成
        </el-button>
      </div>
    </el-dialog>

    <!-- 生成历史对话框 -->
    <el-dialog
      title="生成历史"
      :visible.sync="historyDialog.visible"
      width="70%"
    >
      <generate-history
        v-if="historyDialog.visible"
        :sample-id="historyDialog.sampleId"
      />
    </el-dialog>
  </div>
</template>

<script>
import TestDataView from '@/components/report/TestDataView.vue'
import GenerateHistory from '@/components/report/GenerateHistory.vue'
import { formatDate } from '@/utils/tools'

export default {
  name: 'ReportGeneratorPage',
  components: {
    TestDataView,
    GenerateHistory
  },
  data() {
    return {
      // 筛选表单
      filterForm: {
        templateType: '',
        sampleNo: '',
        dateRange: []
      },
      
      // 数据列表
      dataList: [],
      selectedRows: [],
      loading: false,
      
      // 分页配置
      pagination: {
        current: 1,
        size: 10,
        total: 0
      },
      
      // 项目信息
      currentProjectName: '',
      
      // 对话框控制
      dataViewDialog: {
        visible: false,
        data: null
      },
      
      generateDialog: {
        visible: false,
        title: '生成报告',
        form: {
          templateId: '',
          format: 'word',
          filename: '',
          includes: ['rawData', 'calculations', 'signatures']
        },
        currentData: null
      },
      
      historyDialog: {
        visible: false,
        sampleId: ''
      },
      
      generating: false,
      
      // 模板分组
      templateGroups: []
    }
  },
  created() {
    this.loadProjectInfo()
    this.loadTemplates()
    this.loadDataList()
  },
  methods: {
    /**
     * 加载项目信息
     */
    loadProjectInfo() {
      try {
        const savedConfig = localStorage.getItem('detectionConfig')
        if (savedConfig) {
          const config = JSON.parse(savedConfig)
          this.currentProjectName = config.projectName || '当前项目'
        }
      } catch (error) {
        console.error('加载项目信息失败:', error)
      }
    },
    
    /**
     * 加载模板列表
     */
    loadTemplates() {
      // 模拟模板数据
      this.templateGroups = [
        {
          type: 'record',
          label: '原始记录模板',
          templates: [
            { id: 'template1', name: '钢筋拉伸试验原始记录' },
            { id: 'template2', name: '混凝土抗压原始记录' }
          ]
        },
        {
          type: 'report',
          label: '检测报告模板',
          templates: [
            { id: 'template3', name: '标准检测报告' },
            { id: 'template4', name: '详细检测报告' }
          ]
        }
      ]
      
      // 设置默认模板
      if (this.templateGroups[0] && this.templateGroups[0].templates.length > 0) {
        this.generateDialog.form.templateId = this.templateGroups[0].templates[0].id
      }
    },
    
    /**
     * 加载数据列表
     */
    async loadDataList() {
      this.loading = true
      try {
        // 模拟API调用
        const mockData = this.getMockDataList()
        this.dataList = mockData
        this.pagination.total = mockData.length
      } catch (error) {
        console.error('加载数据列表失败:', error)
        this.$message.error('加载数据列表失败')
      } finally {
        this.loading = false
      }
    },
    
    /**
     * 获取模拟数据
     */
    getMockDataList() {
      return [
        {
          id: 'data001',
          sampleNo: 'SAMPLE-2024-001',
          projectName: '钢筋力学性能检测',
          standardCode: 'GB/T 228.1-2021',
          testDate: '2024-01-20',
          status: 'completed',
          lastGenerateTime: '2024-01-21T10:30:00'
        },
        {
          id: 'data002',
          sampleNo: 'SAMPLE-2024-002',
          projectName: '混凝土抗压强度检测',
          standardCode: 'GB/T 50081-2019',
          testDate: '2024-01-19',
          status: 'completed',
          lastGenerateTime: null
        },
        {
          id: 'data003',
          sampleNo: 'SAMPLE-2024-003',
          projectName: '综合性能检测',
          standardCode: 'JGJ 52-2006',
          testDate: '2024-01-18',
          status: 'testing',
          lastGenerateTime: null
        }
      ]
    },
    
    /**
     * 格式化日期
     */
    formatDate(dateString) {
      return formatDate(dateString, 'YYYY-MM-DD')
    },
    
    /**
     * 获取状态标签样式
     */
    getStatusTag(status) {
      const tagMap = {
        testing: 'warning',
        completed: 'success',
        error: 'danger'
      }
      return tagMap[status] || 'info'
    },
    
    /**
     * 获取状态文本
     */
    getStatusText(status) {
      const textMap = {
        testing: '检测中',
        completed: '已完成',
        error: '异常'
      }
      return textMap[status] || '未知'
    },
    
    /**
     * 处理筛选
     */
    handleFilter() {
      this.pagination.current = 1
      this.loadDataList()
    },
    
    /**
     * 重置筛选
     */
    resetFilter() {
      this.filterForm = {
        templateType: '',
        sampleNo: '',
        dateRange: []
      }
      this.pagination.current = 1
      this.loadDataList()
    },
    
    /**
     * 处理选择变化
     */
    handleSelectionChange(selection) {
      this.selectedRows = selection
    },
    
    /**
     * 查看数据
     */
    viewData(row) {
      // 加载测试数据
      const testData = this.loadTestData(row.id)
      this.dataViewDialog = {
        visible: true,
        data: testData
      }
    },
    
    /**
     * 加载测试数据
     */
    loadTestData(dataId) {
      // 模拟加载测试数据
      return {
        basicInfo: {
          sampleNo: dataId,
          projectName: '示例项目',
          testDate: '2024-01-20'
        },
        groups: [
          {
            groupName: '样品信息',
            params: {
              sample_no: { value: dataId },
              material: { value: 'HRB400' }
            }
          }
        ]
      }
    },
    
    /**
     * 生成单个报告
     */
    generateSingle(row) {
      this.generateDialog = {
        visible: true,
        title: `生成报告 - ${row.sampleNo}`,
        form: {
          templateId: this.generateDialog.form.templateId,
          format: 'word',
          filename: `${row.sampleNo}_报告`,
          includes: ['rawData', 'calculations', 'signatures']
        },
        currentData: row
      }
    },
    
    /**
     * 从数据查看生成报告
     */
    generateFromDataView() {
      if (this.dataViewDialog.data) {
        this.generateSingle({ sampleNo: this.dataViewDialog.data.basicInfo.sampleNo })
        this.dataViewDialog.visible = false
      }
    },
    
    /**
     * 查看生成历史
     */
    viewHistory(row) {
      this.historyDialog = {
        visible: true,
        sampleId: row.id
      }
    },
    
    /**
     * 批量生成
     */
    batchGenerate() {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请选择要生成报告的数据')
        return
      }
      
      this.generateDialog = {
        visible: true,
        title: `批量生成报告 (${this.selectedRows.length}个)`,
        form: {
          templateId: this.generateDialog.form.templateId,
          format: 'word',
          filename: `批量报告_${new Date().getTime()}`,
          includes: ['rawData', 'calculations', 'signatures']
        },
        currentData: this.selectedRows
      }
    },
    
    /**
     * 确认生成
     */
    async confirmGenerate() {
      if (!this.generateDialog.form.templateId) {
        this.$message.error('请选择模板')
        return
      }
      
      this.generating = true
      try {
        const generateData = {
          templateId: this.generateDialog.form.templateId,
          options: this.generateDialog.form,
          data: Array.isArray(this.generateDialog.currentData) 
            ? this.generateDialog.currentData 
            : [this.generateDialog.currentData]
        }
        
        // 调用API生成报告
        // const result = await this.$api.report.batchGenerate(generateData)
        
        // 模拟生成成功
        this.$message.success('报告生成任务已提交')
        this.generateDialog.visible = false
        
        // 如果是单个生成，直接下载
        if (!Array.isArray(this.generateDialog.currentData) || 
            this.generateDialog.currentData.length === 1) {
          this.downloadMockFile()
        }
        
        // 刷新列表
        this.loadDataList()
      } catch (error) {
        console.error('生成报告失败:', error)
        this.$message.error('生成报告失败')
      } finally {
        this.generating = false
      }
    },
    
    /**
     * 模拟下载文件
     */
    downloadMockFile() {
      const blob = new Blob(['模拟报告文件'], { type: 'application/octet-stream' })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `${this.generateDialog.form.filename}.${this.generateDialog.form.format}`
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      URL.revokeObjectURL(url)
    },
    
    /**
     * 刷新
     */
    refresh() {
      this.loadDataList()
      this.$message.success('数据已刷新')
    },
    
    /**
     * 分页大小改变
     */
    handleSizeChange(size) {
      this.pagination.size = size
      this.pagination.current = 1
      this.loadDataList()
    },
    
    /**
     * 当前页改变
     */
    handleCurrentChange(current) {
      this.pagination.current = current
      this.loadDataList()
    }
  }
}
</script>

<style scoped>
.report-generator-page {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 40px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.page-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.filter-container {
  margin: 20px 0;
  padding: 20px;
  background: white;
  border-radius: 4px;
}

.data-table {
  margin: 20px 0;
}

.sample-no {
  font-weight: 600;
  color: #409eff;
}

.project-info {
  line-height: 1.4;
}

.project-name {
  font-weight: 500;
  color: #303133;
}

.standard-code {
  font-size: 12px;
  color: #909399;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .report-generator-page {
    padding: 15px;
  }
  
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .header-actions {
    width: 100%;
    justify-content: flex-start;
    flex-wrap: wrap;
  }
  
  .filter-container .el-form--inline .el-form-item {
    margin-bottom: 10px;
  }
}

@media (max-width: 768px) {
  .report-generator-page {
    padding: 10px;
  }
  
  .filter-container {
    padding: 15px;
  }
}
</style>